<template>
  <view
    class="xh-toast"
    id="xh-toast"
    :style="{
      zIndex: zIndex,
      transform: `scale(${visible ? 1 : 0})`,
      backgroundColor: mask && `rgba(61,61,61,${visible ? '.6' : '0'})`,
    }"
  >
    <view class="xh-toast-content" @click.stop v-if="visible">
      <view class="xh-toast-type" v-if="type !== 'text'">
        <loading v-if="type === 'loading'" :size="addUnit(iconSize)" />
      </view>
      <view
        class="xh-toast-message"
        :style="{
          fontSize: addUnit(fontSize),
        }"
        >{{ message }}</view
      >
    </view>
  </view>
</template>
<script>
function number(value) {
  return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value);
}
import loading from "./loading";
export default {
  name: "Toast",
  components: {
    loading,
  },
  data() {
    return {
      visible: false,
      this: null,
    };
  },
  props: {
    show: Boolean,
    mask: Boolean,
    message: String,
    type: {
      type: String,
      default: "text",
    },
    zIndex: {
      type: Number,
      default: 1000,
    },
    duration: {
      type: Number,
      default: 2000,
    },
    iconSize: {
      type: [String, Number],
      default: 80,
    },
    fontSize: {
      type: [String, Number],
      default: 28,
    },
    selector: {
      type: String,
      default: "#xh-toast",
    },
  },

  watch: {
    show(val) {
      this.visible = val;
      if (val) {
        this.$emit("onOpened");
        if (this.duration != null && this.duration > 0) {
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.visible = false;
            this.$emit("onClose");
          }, this.duration);
        }
      } else {
        this.$emit("onClose");
      }
    },
  },
  methods: {
    addUnit(value = "auto", unit = "rpx") {
      value = String(value);
      // 用uView内置验证规则中的number判断是否为数值
      return number(value) ? `${value}${unit}` : value;
    },
  },
};
</script>
<style lang="scss" scoped>
.xh-toast {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.1s;
  &-content {
    width: auto;
    background-color: #fff;
    border-radius: 15rpx;
    padding: 20rpx;
  }
  &-type {
    display: flex;
    justify-content: center;
    margin-bottom: 10rpx;
  }
  &-message {
    text-align: center;
  }
}
</style>
